﻿var standard_add = {
    init: function() {
        var that = this;

        $.ajax({
            url: COMMONURL + 'api/company/getcompanyinfo',
            type: 'get',
            data: {
                token: $.cookie('token')
            },
            dataType: 'json',
            beforeSend: function () {
                $('.jload').show();
            },
            complete: function () {
                $('.jload').hide();
            }
        }).done(function (data) {
            var value = data.mod;
            if (!!value) {
                var cityIdArray = value.city_id_x ? value.city_id_x.split('|') : [];
                var area = cityIdArray[0] == undefined ? '' : cityIdArray[0];
                var city = cityIdArray[1] == undefined ? '' : cityIdArray[1];
                var town = cityIdArray[2] == undefined ? '' : cityIdArray[2];
                that.getoAddress({
                    type: 10
                }, $("#start_pro_id"), function () {
                    if (area != '') {
                        $("#start_pro_id option").each(function (i, t) {
                            if ($(t).attr('data-id') == area) {

                                $(t).attr('selected', true);
                            }
                        })
                    }

                    $("#start_address").val(value.address);

                    that.getoAddress({
                        type: 20,
                        sub_city_id: area
                    }, $("#start_city_id"), function () {
                        if (city != '') {
                            $("#start_city_id option").each(function (i, t) {
                                if ($(t).attr('data-id') == city) {
                                    $(t).attr('selected', true);
                                }
                            })
                        }

                        that.getoAddress({
                            type: 30,
                            sub_city_id: city
                        }, $("#start_town_id"), function () {
                            if (town != '') {
                                $("#start_town_id option").each(function (i, t) {
                                    if ($(t).attr('data-id') == town) {
                                        $(t).attr('selected', true);
                                    }
                                })
                            }

                        });
                    });
                });
                
            }

        })
        //$("#standardAdd").html($("#addItemTpl").html());
        that.dateInit();
        that.getAddress(10, '', $("select[data-name=oprovince]"));
        that.getAddress(20, '', $("select[data-name=ocity]"));
        that.getAddress(30, '', $("select[data-name=otown]"));
        
        
         
        that.getGoodsHour();
        that.doSubmit();
        that.getStaffList();
        that.getContactsList();
        //添加目的地
        var $receipt = $('[data-name="receipt"]'),
            $add = $('#add'),
            $receiptAdd = $("#receiptAdd");
        var addCount = 0;
        $add.click(function() {
            addCount += 1;
            var tpl = ' <div class="group jgroupList" data-name="address_add">\
                            <label class="l-label">收 货 地' + addCount + '：</label>\
                            <div class="l-area">\
                                <div class="col1">\
                                    <select class="select select1"  data-name="province"></select>\
                                    <select class="select select1"  data-name="city"></select>\
                                    <select class="select select1" data-name="town"></select>\
                                </div>\
                                <div class="col1">\
                                     <input class="input input2" name="detail" placeholder="详细地址" >\
                                </div>\
                            </div>\
                            <a href="javascript:;" class="remove_address jremoveAddress">移除该地址</a>\
                        </div>';
            $receiptAdd.append(tpl);
            that.getAddress(10, '', $('select[data-name="province"]'));
            that.getAddress(20, '', $('select[data-name="city"]'));
            that.getAddress(30, '', $('select[data-name="town"]'));




            $("#receiptAdd").attr('data-isset', '1');
        });

        $("#receiptAdd").on("click", ".jremoveAddress", function(){
                $(this).parent(".jgroupList").remove();
        })


        $("#start_pro_id").change(function() {
            var $this = $(this);
            that.getoAddress({
                type: 20,
                sub_city_id: $this.find(':selected').attr('data-id')
            }, $("#start_city_id"), function() {
                that.getoAddress({
                    type: 30,
                    sub_city_id: $("#start_city_id option").eq(0).attr('data-id')
                }, $("#start_town_id"));
            });
        })

        $("#start_city_id").change(function() {
            var $this = $(this);
            that.getoAddress({
                type: 30,
                sub_city_id: $this.find(':selected').attr('data-id')
            }, $("#start_town_id"));
        })

        $("#end_pro_id").change(function() {
            var $this = $(this);
            that.getoAddress({
                type: 20,
                sub_city_id: $this.find(':selected').attr('data-id')
            }, $("#end_city_id"), function() {
                that.getoAddress({
                    type: 30,
                    sub_city_id: $("#end_city_id option").eq(0).attr('data-id')
                }, $("#end_town_id"));
            });
        })

        $("#end_city_id").change(function() {
            var $this = $(this);
            that.getoAddress({
                type: 30,
                sub_city_id: $this.find(':selected').attr('data-id')
            }, $("#end_town_id"));
        })
        

        $('body').on('change', '[data-name="province"]', function() {
            var _self = $(this),
                sub = _self.find('option:selected').attr('data-id');
            that.getAddress(20, sub, _self.next('[data-name="city"]'));
        });

        $('body').on('change', '[data-name="city"]', function() {
            var _self = $(this),
                sub = _self.find('option:selected').attr('data-id');
            that.getAddress(30, sub, _self.next('[data-name="town"]'));
        });

       

        $('input[name="danger"]').click(function(){
            var index = $('input[name="danger"]').index($(this))
            if(index==0){
                $('#wuliu_type option[text=0]').attr('selected','selected');
            }else if(index==1 || index==2){
                $('#wuliu_type option[text=1]').attr('selected','selected');
            }
        })
    },
    getGoodsHour: function() {
        //取货时间
        var $start_receipt_hour = $("#start_receipt_hour"),
            $end_receipt_hour = $("#end_receipt_hour"),
            default_start = 0;
        default_end = 24;

        initTime(default_start, default_end, $start_receipt_hour);
        initTime(default_start, default_end, $end_receipt_hour);

        $start_receipt_hour.change(function() {
            var val = +$(this).val();
            initTime(val + 1, default_end, $end_receipt_hour);
        });

        $end_receipt_hour.change(function() {
            var val = +$(this).val();
            initTime(default_start, val, $start_receipt_hour);
        });

        function initTime(start, end, $obj) {
            var tpl = [];
            for (var i = start; i < end; i++) {
                tpl.push('<option value="' + i + '">' + i + '</option>');
            }
            $obj.html(tpl.join(""));
        }

    },
    dateInit: function() {
        $('.datepicker').datetimepicker({
             language: 'zh-CN',
            weekStart: 1,
            todayBtn: 1,
            autoclose: 1,
            todayHighlight: 1,
            startView: 2,
            forceParse: 0,
            showMeridian: 1,
            format: 'yyyy/mm/dd hh:ii'
        });

        Date.prototype.dateFormat=function(fmt) {         
        var o = {         
            "M+" : this.getMonth()+1, //月份         
            "d+" : this.getDate(), //日         
            "h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小时         
            "H+" : this.getHours(), //小时         
            "m+" : this.getMinutes(), //分         
            "s+" : this.getSeconds(), //秒         
            "q+" : Math.floor((this.getMonth()+3)/3), //季度         
            "S" : this.getMilliseconds() //毫秒         
        };         
        var week = {         
            "0" : "\u65e5",         
            "1" : "\u4e00",         
            "2" : "\u4e8c",         
            "3" : "\u4e09",         
            "4" : "\u56db",         
            "5" : "\u4e94",         
            "6" : "\u516d"        
        };         
        if(/(y+)/.test(fmt)){         
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));         
        }         
        if(/(E+)/.test(fmt)){         
            fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "\u661f\u671f" : "\u5468") : "")+week[this.getDay()+""]);         
        }         
        for(var k in o){         
            if(new RegExp("("+ k +")").test(fmt)){         
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));         
            }         
        }         
        return fmt;         
    } 
       
    var now = new Date();
    var nowAdd = new Date(now.valueOf()+3*60*60*1000).dateFormat("yyyy/MM/dd HH:mm");
    
     $("#consignee_time").val(nowAdd);
     $("#start_bid_time").val(now.dateFormat("yyyy/MM/dd HH:mm"))
    },
    getoAddress: function(type, obj, callback) {
        $.ajax({
            url: COMMONURL + 'api/CityBase/GetCityBaseList?token=' + $.cookie('token'),
            type: 'post',
            dataType: 'json',
            data: type

        }).done(function(data) {
            var arry = [];
            if (!!data.mod) {
                if (!data.mod.length) {
                    arry.push('<option value="' + '" data-id="' + '">' + '请选择' + '</option>');
                } else {
                    $.each(data.mod, function(i, v) {
                        arry.push('<option value="' + v.city_name + '" data-id="' + v.city_id + '">' + v.city_name + '</option>');
                    });
                }
    
                obj.html(arry.join(''));
                if (typeof callback == 'function') {
                    callback();
                }
            }

        })
    },
    getAddress: function(type, sub, obj) {
        $.ajax({
            url: COMMONURL + 'api/CityBase/GetCityBaseList?token=' + $.cookie('token'),
            type: 'post',
            dataType: 'json',
            data: {
                type: type,
                sub_city_id: sub
            }

        }).done(function(data) {
            var arry = [];
            if (!!data.mod) {
                if (!data.mod.length) {
                    arry.push('<option value="' + '" data-id="' + '">' + '请选择' + '</option>');
                } else {
                    $.each(data.mod, function(i, v) {
                        arry.push('<option value="' + v.city_name + '" data-id="' + v.city_id + '">' + v.city_name + '</option>');
                    });
                }
                obj.html(arry.join(''));
            }

        })
    },
    getStaffList: function() {
        $.ajax({
            url: COMMONURL + "api/companysale/get?token=" + $.cookie('token'),
            type: "get",
            dataType: "json"
        }).done(function(redata) {
        		if(redata.recode=='1003'){
                window.location.href = '/nlogin.html';
                return;}
            if (redata.recode == '0000') {
                var s = [];
                if (redata.mod) {
                    for (var i = 0; i < redata.mod.length; i++) {
                       s.push('<option value="'+redata.mod[i].sales_phone+'">' + redata.mod[i].sales_name + '</option>');
                    }
                    $("#staff").html(s.join(''));
                }
            }
        });
    },
    getContactsList:function(){
        $.ajax({
            url: COMMONURL + "api/Account/GetContactsList?token=" + $.cookie('token'),
            type: "post",
            dataType: "json"
        }).done(function(redata) {
        		if(redata.recode=='1003'){
                window.location.href = '/nlogin.html';
                return;}
            if (redata.recode == '0000') {
                var s = [];
                if (redata.mod) {
                    for (var i = 0; i < redata.mod.length; i++) {
                        s.push('<option value="'+redata.mod[i].phone+'">' + redata.mod[i].nick_name + '</option>');
                    }
                    $("#contacts").html(s.join(''));
                }
            }
        });
    },
    doSubmit: function() {
       

        $("#addItem").validate({
            errorClass: 'error',
            rules: {
                start_address: "required",
                consignee_time: 'required',
                end_address: "required",
                receipt_time: 'required',
                start_bid_time: "required",
                //number: "required",
                 information:"required",
                wuliu_type: "required"
               // start_city_name: "required",
               // end_city_name: "required"
                    /* end_address2:{
                        isAddress:true
                     }*/
            },
            messages: {
                start_address: "",
                consignee_time: '',
                end_address: "",
                receipt_time: '',
                start_bid_time: "",
                number: "",
                information:"",
                wuliu_type: ""
              //  start_city_name: "",
              //  end_city_name: ""
                    /* end_address2:{
                        isAddress:''
                     }*/
            },
            submitHandler: function(form) {
                var start_city_id = $.trim($("#start_town_id option:selected").attr('data-id')),
                    start_city_id_x = $.trim($("#start_pro_id option:selected").attr('data-id')) + '|' + $.trim($("#start_city_id option:selected").attr('data-id')) + '|' + start_city_id,
                    // start_city_name = $("#start_pro_id").val() + '|' + $("#start_city_id").val() + '|' + $("#start_town_id").val(),
                    start_city_name =   $("#start_pro_id").val()+$("#start_city_id").val()+$("#start_town_id").val(),
                    start_address = $.trim($("#start_address").val()),
                    consignee_time = $("#consignee_time").val(),
                    end_city_id = $("#end_town_id option:selected").attr('data-id'),
                    end_city_id_x = $("#end_pro_id option:selected").attr('data-id') + "|" + $("#end_city_id option:selected").attr('data-id') + "|" + end_city_id,
                    //end_city_name = $("#end_pro_id").val() + '|' + $("#end_city_id").val() + '|' + $("#end_town_id").val(),
                    end_city_name = $("#end_pro_id").val()+$("#end_city_id").val()+$("#end_town_id").val(),
                    end_address = $.trim($("#end_address").val());
                var end_city_id2 = end_city_name2 = end_address2 = end_city_id2_x = '';
                $("#receiptAdd [data-name='address_add']").each(function() {
                    var city_id = $(this).find('[data-name="town"] option:selected').attr('data-id'),
                        city_id_x = $(this).find('[data-name="province"] option:selected').attr('data-id') + '|' + $(this).find('[data-name="city"] option:selected').attr('data-id') + '|' + city_id,
                        //city_name = $(this).find('[data-name="province"]').val() + '|' + $(this).find('[data-name="city"] ').val() + '|' + $(this).find('[data-name="town"]').val(),
                        city_name = $(this).find('[data-name="province"]').val()+$(this).find('[data-name="city"]').val()+$(this).find('[data-name="town"]').val(),
                        address = $(this).find('[name="detail"]').val();
                    end_city_id2 = end_city_id2 + city_id + ';';
                    end_city_name2 = end_city_name2 + city_name + ';';
                    end_address2 = end_address2 + address+';';
                    end_city_id2_x = end_city_id2_x+city_id_x+';';
                });
                var start_bid_time = $("#start_bid_time").val(),
                    end_bid_time=  $('[name="end_bid_time"]:checked').val()==-1?new Date($('#editendbid_other').val()).getTime():parseInt($('[name="end_bid_time"]:checked').val()) * 60000 + new Date(start_bid_time).getTime(),
                   // end_bid_time = parseInt($('[name="end_bid_time"]:checked').val()) * 60000 + new Date(start_bid_time).getTime(),
                    danger = $('[name="danger"]:checked').val(),
                    wuliu_type = $("#wuliu_type option:selected").attr("value"),
                    number = $("#number").val(),
                    information = $("#information").val(),
                    remark = $("#remark").val(),
                    start_receipt_hour = $("#start_receipt_hour").val(),
                    end_receipt_hour = $("#end_receipt_hour").val(),
                    receipt_time = $("#receipt_time").val(),
                    contacts = $("#contacts option:selected").text(),
                    contacts_phone = $("#contacts option:selected").val(),
                    staff = $("#staff option:selected").text(),
                    staff_off = $("#staff option:selected").val();

                var data = {
                    start_city_id: start_city_id,
                    start_city_name: start_city_name,
                    start_address: start_address,
                    start_city_id_x: start_city_id_x,
                    end_city_id: end_city_id,
                    end_city_name: end_city_name,
                    end_address: end_address,
                    end_city_id_x: end_city_id_x,
                    end_city_id2: end_city_id+';'+end_city_id2,
                    end_city_name2: end_city_name+';'+end_city_name2,
                    end_address2: end_address+';'+end_address2,
                    end_city_id2_x:end_city_id_x+';'+end_city_id2_x,
                    start_bid_time: new Date(start_bid_time).getTime(),
                    end_bid_time: end_bid_time,
                    consignee_time: new Date(consignee_time).getTime(),
                    receipt_time: new Date(receipt_time).getTime(),
                    start_receipt_hour: start_receipt_hour,
                    end_receipt_hour: end_receipt_hour,
                    remark:remark,
                    danger: danger,
                    wuliu_type: wuliu_type,
                    information: information,
                    contacts: contacts,
                    contacts_phone: contacts_phone,
                    staff: staff,
                    staff_phone: staff_off,
                    number: number
                }
               
                $.ajax({
                    url: COMMONURL + "api/BidBase/addbidbase?token=" + $.cookie('token'),
                    type: "post",
                    dataType: "json",
                    data: data,
                }).done(function(data) {
                    /* if(data.recode == '0000'){
                         $.blockUI({
                             message:redata.resmessage
                         });
                     }else{
                         $.blockUI({
                             message:redata.resmessage
                         });
                     }*/
	        if(data.recode=='1003'){
                window.location.href = '/nlogin.html';
                return;}
                    if (data.recode == '0000') {
                        alert('操作成功');
                        	//window.location.href = '/#Standard_List';
                           window.location.reload();
                    } else {
                        alert(data.resmessage);
                    }
                })
            }
        })
    }
}
